/*
 * Filename:    InsuredMedicalDetailServiceImpl.java
 * Copyright:   2015 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2015-1-28
 */
package com.paic.mhis.hcpms.trust.biz.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.common.base.dto.PaginationDTO;
import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.common.util.Constants;
import com.paic.mhis.common.util.PageUtil;
import com.paic.mhis.hcpms.trust.biz.service.InsuredMedicalDetailService;
import com.paic.mhis.hcpms.trust.dto.IntegrityDoctorDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityMedicalDTO;
import com.paic.mhis.hcpms.trust.dto.PointCutDTO;
import com.paic.mhis.hcpms.trust.intergration.dao.InsuredMedicalDetailDAO;
import com.paic.mhis.hcpms.trust.intergration.dao.IntegrityArtificialScoreDAO;

@Component("insuredMedicalDetailService")
public class InsuredMedicalDetailServiceImpl implements InsuredMedicalDetailService {
	private static final Logger logger = Logger.getLogger(InsuredMedicalDetailServiceImpl.class);
	@Autowired
	private CommonDAO commonDAO;
	@Autowired
	private InsuredMedicalDetailDAO insuredMedicalDetailDao;
	@Autowired
	private IntegrityArtificialScoreDAO integrityArtificialScoreDao;

	@Override
	public Map<String, Object> getMedicalDetailList(Map<Object, Object> paramMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			PaginationDTO pdto = new PaginationDTO();
			pdto.setDoCount(true);// 查询总条数
			pdto.setQueryAll(false);// 不查询所有记录
			pdto.setQueryParams(paramMap);
			pdto.setStart(Integer.parseInt(paramMap.get("start").toString()));
			pdto.setEnd(Integer.parseInt(paramMap.get("limit").toString())
					+ Integer.parseInt(paramMap.get("start").toString()));
			resultMap = commonDAO.queryPage("integrityDesc.findIntegrityDescs", pdto);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return resultMap;
	}

	@Override
	public int getCountMedicalDetailReport(Map<Object, Object> paramMap) {
		return insuredMedicalDetailDao.getCountMedicalDetailReport(paramMap);
	}

	/**
	 * 根据医务人员证件号码查询姓名及执业医院信息
	 * 
	 * @param map
	 * @return
	 */
	@Override
	public List<IntegrityDoctorDTO> queryIntegrityDoctor(Map<String, Object> map) {
		return integrityArtificialScoreDao.queryIntegrityDoctor(map);
	}

	/**
	 * 根据任务编号查询执业医院列表信息
	 * 
	 * @param map
	 * @return
	 */
	@Override
	public List<IntegrityDoctorDTO> queryIntegrityDoctorList(String taskNo) {
		return integrityArtificialScoreDao.queryIntegrityDoctorList(taskNo);
	}

	/**
	 * 获取流程编号
	 * 
	 * @return
	 */
	@Override
	public String queryIntegrityNo() {
		return integrityArtificialScoreDao.queryIntegrityNo();
	}

	// /**
	// * 保存
	// *
	// * @param transferJson
	// * @param userName
	// * @param caseNo
	// * @param caseType
	// * @return
	// */
	// @Override
	// @Transactional
	// public Map<String, Object> saveIntegrityDoctor(JSONObject transferJson,
	// String userName) throws BusinessException {
	// Map<String, Object> result = new HashMap<String, Object>();
	// if (transferJson == null || transferJson.equals(new JSONObject())) {
	// return result;
	// }
	// String taskNo = transferJson.getString("taskNo");// 任务编号
	// if (StringUtils.isBlank(taskNo)) {
	// taskNo = queryIntegrityNo();
	// result.put("taskNo", taskNo);
	// // 扣分
	// integrityMedicalService.addIntegrityPoints(transferJson, userName,
	// taskNo, TrustConstants.CASE_TYPE);
	// } else {
	// integrityMedicalService.addIntegrityPointTemps(transferJson, userName);
	// }
	// // InsuranceTaskDTO taskDTO = new InsuranceTaskDTO();// 医务人员任务
	// updateCredentials(taskNo, transferJson);
	// result.put(WarnConstants.STATE_KEY, WarnConstants.SUCCESS_STATE_VALUE);
	// result.put(WarnConstants.MSG_KEY, WarnConstants.SAVE_SUCCESS);
	// return result;
	// }

	/**
	 * 保存证件信息表
	 * 
	 * @param paramter
	 * @return
	 */
	public int updateCredentials(String taskNo, JSONObject transferJson) {
		String certifiNo = transferJson.getString("certifiNo");// 证件类型
		String certifiType = transferJson.getString("certifiType");// 证件编号
		String orgCode = transferJson.getString("orgCode");// 机构编号
		String dateStart = transferJson.getString("workDateStart");// 执业开始时间
		String dateEnd = transferJson.getString("workDateEnd");// 执业结束时间
		Map<String, Object> paramter = new HashMap<String, Object>();
		paramter.put("taskNo", taskNo);
		paramter.put("credentialsNo", certifiNo);
		paramter.put("credentialsType", certifiType);
		paramter.put("orgCode", orgCode);
		paramter.put("dateStart", dateStart);
		paramter.put("dateEnd", dateEnd);
		return integrityArtificialScoreDao.updateCredentials(paramter);
	}

	// /**
	// * 撤回
	// */
	// public Map<String, Object> backWarnProcess(String taskNo, String status,
	// UserDetails user) throws Exception {
	// Map<String, Object> result = new HashMap<String, Object>();
	// // 启动
	// Map<String, String> condition = new HashMap<String, String>();
	// if (TrustConstants.STATUS_WAIT_AUDIT.equals(status)) {
	// condition.put("AUDIT_OPINION", TrustConstants.INTEGRITY_OPINION_NO);
	// }
	// // 判断节点是否已经发生变化
	// String actCurrent = integrityWorkFlowService.startWorkFlow(taskNo, user,
	// condition);
	// if (!actCurrent.equals(status)) {
	// result.put(TrustConstants.STATE_KEY, TrustConstants.PROCESS_NOT_POWER);
	// result.put(TrustConstants.MSG_KEY,
	// TrustConstants.PROCESS_NOT_POWER_ERROR);
	// return result;
	// }
	// // 流程
	// HcpmsWorkFlowVO wfvo = new HcpmsWorkFlowVO();
	// wfvo.setTaskNo(taskNo);
	// wfvo.setActCurrent(user.getUsername());
	// wfvo.setParamValue(condition);
	// actCurrent = integrityWorkFlowService.processWorkFlow(wfvo);
	// // 更新状态
	// HcpmsWFTaskDTO taskDto = new HcpmsWFTaskDTO();
	// taskDto.setTaskNo(taskNo);
	// taskDto.setUpdatedBy(user.getUsername());
	// taskDto.setActCurrent(actCurrent);
	// taskDto.setAssigner(user.getUsername());
	// taskDto.setAuthorizerType(TrustConstants.PERSON_TYPE);
	// integrityWFDAO.updateWorkFlowTask(taskDto);
	// result.put(TrustConstants.STATE_KEY, TrustConstants.SUCCESS_STATE_VALUE);
	// result.put(TrustConstants.MSG_KEY,
	// TrustConstants.WARN_PROCESS_REST_SUCCESS);
	// return result;
	// }

	// /**
	// * 查询扣分信息
	// *
	// * @param taskNo
	// * @param status
	// * @param user
	// * @return
	// * @throws Exception
	// */
	// public Map<String, Object> integrityArtificialScoreInfo(String taskNo,
	// UserDetails user) throws Exception {
	// Map<String, Object> result = new HashMap<String, Object>();
	// Map<String, Object> paramMap = new HashMap<String, Object>();
	// paramMap.put("caseType", TrustConstants.CASE_TYPE);
	// paramMap.put("caseNo", taskNo);
	// paramMap.put("userName", user.getUsername());
	// List<PointCutDTO> pointList =
	// integrityMedicalService.findPointCutStorageCollections(paramMap);
	// result.put("pointList", pointList);
	// List<IntegrityDoctorDTO> integrityList =
	// this.queryIntegrityDoctorList(taskNo);
	// result.put("integrityList", integrityList);
	// result.put("integrityInfo", this.queryIntegrityDoctorByTaskNo(taskNo));
	// return result;
	// }

	/**
	 * 根据流程编号查询姓名及执业医院信息
	 * 
	 * @param map
	 * @return
	 */
	@Override
	public IntegrityDoctorDTO queryIntegrityDoctorByTaskNo(String taskNo) {
		List<IntegrityDoctorDTO> list = integrityArtificialScoreDao.queryIntegrityDoctorByTaskNo(taskNo);
		return list.size() > 0 ? list.get(0) : null;
	}

	/**
	 * 医务人员登记查询
	 */
	@Override
	public Map<String, Object> insuredMedicalListAdd(Map<Object, Object> paramMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			PaginationDTO pdto = new PaginationDTO();
			pdto.setDoCount(true);// 查询总条数
			pdto.setQueryAll(false);// 不查询所有记录
			pdto.setQueryParams(paramMap);
			pdto.setStart(Integer.parseInt(paramMap.get("start").toString()));
			pdto.setEnd(Integer.parseInt(paramMap.get("limit").toString())
					+ Integer.parseInt(paramMap.get("start").toString()));
			resultMap = commonDAO.queryPage("integrityscore.queryInsuredMedicalListAdd", pdto);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return resultMap;
	}

	/**
	 * 医务人员登记导出查询(暂存表待修改的数据)
	 * 
	 * @param paramMap
	 * @return
	 */
	@Override
	public List<IntegrityMedicalDTO> insuredMedicalListAddExport(Map<Object, Object> paramMap) {
		PaginationDTO pdto = new PaginationDTO();
		pdto.setDoCount(true);// 查询总条数
		pdto.setQueryAll(false);// 不查询所有记录
		pdto.setQueryParams(paramMap);
		List<IntegrityMedicalDTO> storateList = integrityArtificialScoreDao.insuredMedicalListAddExport(pdto);
		for (IntegrityMedicalDTO dto : storateList) {
			JSONObject json = (JSONObject) JSONObject.parse(dto.getDataBlob());
			JSONArray jsonArr = (JSONArray) json.get("warnMarkTempDetails");
			if (jsonArr != null) {
				if (jsonArr.size() > 0) {
					JSONObject tempJson = jsonArr.getJSONObject(0);
					// 医务人员
					JSONArray deducitonStaffs = (JSONArray) tempJson.get("deducitonStaffs");// 医务人员录入记分有且只有一条记分值
					PointCutDTO pointCut = JSONObject.toJavaObject(deducitonStaffs.getJSONObject(0), PointCutDTO.class);
					dto.setReason(pointCut.getReason());
					dto.setPunishDateStart(pointCut.getPunishDateStart());
					dto.setPunishDateEnd(pointCut.getPunishDateEnd());
				}
			}
		}
		return storateList;
	}

	/**
	 * 医务人员登记导出查询(临时表待修改的数据)
	 * 
	 * @param paramMap
	 * @return
	 */
	public List<IntegrityMedicalDTO> insuredMedicalListAddExportTemp(Map<Object, Object> paramMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		PaginationDTO pdto = new PaginationDTO();
		pdto.setDoCount(true);// 查询总条数
		pdto.setQueryAll(false);// 不查询所有记录
		pdto.setQueryParams(paramMap);
		List<IntegrityMedicalDTO> tempList = integrityArtificialScoreDao.insuredMedicalListAddExportTemp(pdto);
		resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
		resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		return tempList;
	}

	@Override
	public List<IntegrityMedicalDTO> findMedicalDetailReport(int pageSize, int currentPage, Map<Object, Object> paramMap) {
		// 如果没有分页值则初始化值
		PageUtil.assemblePageParamObject(pageSize, currentPage, paramMap);
		return insuredMedicalDetailDao.findMedicalDetailReport(paramMap);
	}

	@Override
	public String exportIntegrityIllegalToCsv(Map<String, Object> paramMap) throws IOException {
		StringBuilder sb = new StringBuilder();
		File f = new File("tempFile.txt");
		OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream(f), "gbk");
		Map<String, Object> warnResultMap = queryIntegrityIllegal(paramMap);
		@SuppressWarnings("unchecked")
		Map<String, Object> warnData = (Map<String, Object>) warnResultMap.get("warnData");
		@SuppressWarnings("unchecked")
		Map<String, Object> auditData = (Map<String, Object>) warnResultMap.get("auditData");
		wr.write(paramMap.get("orgName") + "违规情况:,");
		sb.append(paramMap.get("orgName") + "违规情况:,");
		wr.write("\r\n");
		sb.append("\r\n");
		wr.write("\r\n");
		sb.append("\r\n");
		wr.write(",1、预警次数：,");
		sb.append(",1、预警次数：,");
		wr.write(",");
		sb.append(",");
		wr.write(warnData.get("num") == null ? "0" : warnData.get("num").toString());
		sb.append(warnData.get("num") == null ? "0" : warnData.get("num").toString());
		wr.write("次,");
		sb.append("次,");
		wr.write(",");
		sb.append(",");
		wr.write("涉及金额:,");
		sb.append("涉及金额:,");
		wr.write(warnData.get("money") == null ? "0" : warnData.get("money") + ",");
		sb.append(warnData.get("money") == null ? "0" : warnData.get("money") + ",");
		wr.write("元,");
		sb.append("元,");
		wr.write("\r\n");
		sb.append("\r\n");
		// 预警次数结束
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> list = (List<Map<String, Object>>) warnData.get("list");
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, Object> tempMap = (HashMap<String, Object>) list.get(i);
			wr.write(",");
			if (i == 0) {
				wr.write("其中:" + ",");
				sb.append("其中:" + ",");
			} else {
				wr.write(",");
				sb.append(",");
			}
			wr.write(tempMap.get("name") + ":,");
			sb.append(tempMap.get("name") + ":,");
			/*
			 * wr.write(tempMap.get("sumamount") == null ? "0" :
			 * tempMap.get("sumamount").toString());
			 * sb.append(tempMap.get("sumamount") == null ? "0" :
			 * tempMap.get("sumamount").toString());
			 */
			wr.write(tempMap.get("num") == null ? "0" : tempMap.get("num").toString());
			sb.append(tempMap.get("num") == null ? "0" : tempMap.get("num").toString());
			wr.write("次,");
			sb.append("次,");
			wr.write(",");
			sb.append(",");
			wr.write("涉及金额:,");
			sb.append("涉及金额:,");
			wr.write(tempMap.get("money") == null ? "0" : tempMap.get("money") + ",");
			sb.append(tempMap.get("money") == null ? "0" : tempMap.get("money") + ",");
			wr.write("元,");
			sb.append("元,");
			wr.write("\r\n");
			sb.append("\r\n");
		}
		wr.write("\r\n");
		sb.append("\r\n");
		// 预警结束
		wr.write(",");
		sb.append(",");
		wr.write("2、稽核次数:,");
		sb.append("2、稽核次数:,");
		wr.write(",");
		sb.append(",");
		wr.write(auditData.get("num") == null ? "0" : auditData.get("num") + "次,");
		sb.append(auditData.get("num") == null ? "0" : auditData.get("num") + "次,");
		wr.write(",");
		sb.append(",");
		wr.write("涉及金额：,");
		sb.append("涉及金额：,");
		wr.write(auditData.get("money") == null ? "0" : auditData.get("money") + ",");
		sb.append(auditData.get("money") == null ? "0" : auditData.get("money") + ",");
		wr.write("元,");
		sb.append("元,");
		wr.write("\r\n");
		sb.append("\r\n");
		wr.write("\r\n");
		sb.append("\r\n");
		// 稽核结束
		wr.write(",");
		sb.append(",");
		wr.write("3、其中一次记十二分:,");
		sb.append("3、其中一次记十二分:,");
		wr.write(",");
		sb.append(",");
		wr.write("(填充数据)" + "次,");
		sb.append("(填充数据)" + "次,");
		wr.write("\r\n");
		sb.append("\r\n");
		wr.write("\r\n");
		sb.append("\r\n");
		// 12分结束
		wr.write(",");
		sb.append(",");
		wr.write("4、FWA事后审核情况:" + ",");
		sb.append("4、FWA事后审核情况:" + ",");
		wr.write("\r\n");
		sb.append("\r\n");
		// 1
		wr.write(",");
		sb.append(",");
		wr.write(",");
		sb.append(",");
		wr.write("单据数:" + ",");
		sb.append("单据数:" + ",");
		wr.write("0条" + ",");
		sb.append("0条" + ",");
		wr.write(",");
		sb.append(",");
		wr.write("涉及金额:" + ",");
		sb.append("涉及金额:" + ",");

		wr.write("0,元" + ",");
		sb.append("0,元" + ",");
		wr.write("\r\n");
		sb.append("\r\n");
		// first row end
		wr.write(",");
		sb.append(",");
		wr.write("其中:,");
		sb.append("其中:,");
		wr.write("可疑:" + ",");
		sb.append("可疑:" + ",");
		wr.write("0条" + ",");
		sb.append("0条" + ",");
		wr.write(",");
		sb.append(",");
		wr.write("涉及金额:" + ",");
		sb.append("涉及金额:" + ",");

		wr.write("0,元" + ",");
		sb.append("0,元" + ",");
		wr.write("\r\n");
		sb.append("\r\n");
		// two end
		wr.write(",");
		sb.append(",");
		wr.write(",");
		sb.append(",");
		wr.write("高度可疑:" + ",");
		sb.append("高度可疑:" + ",");
		wr.write("0条" + ",");
		sb.append("0条" + ",");
		wr.write(",");
		sb.append(",");
		wr.write("涉及金额:" + ",");
		sb.append("涉及金额:" + ",");

		wr.write("0,元" + ",");
		sb.append("0,元" + ",");
		wr.write("\r\n");
		sb.append("\r\n");
		// three end
		wr.write(",");
		sb.append(",");
		wr.write(",");
		sb.append(",");
		wr.write("违规:" + ",");
		sb.append("违规:" + ",");
		wr.write("0条" + ",");
		sb.append("0条" + ",");
		wr.write(",");
		sb.append(",");
		wr.write("涉及金额:" + ",");
		sb.append("涉及金额:" + ",");

		wr.write("0,元" + ",");
		sb.append("0,元" + ",");
		wr.write("\r\n");
		sb.append("\r\n");
		// four end
		wr.flush();
		wr.close();
		// return f;
		return sb.toString();
	}

	@Override
	public Map<String, Object> queryIntegrityIllegal(Map<String, Object> map) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 查询预警次数以及涉及金额
		List<Map<String, Object>> warnList = insuredMedicalDetailDao.queryIntegrityIllegalWarn(map);
		Map<String, Object> warnData = warnList.size() > 0 ? warnList.get(0) : new HashMap<String, Object>();
		// 提醒次数
		map.put("process", "01");
		List<Map<String, Object>> list01 = insuredMedicalDetailDao.queryIntegrityIllegalWarn(map);
		Map<String, Object> map01 = list01.size() > 0 ? list01.get(0) : new HashMap<String, Object>();
		map01.put("code", "01");
		map01.put("name", "提醒");
		list.add(map01);
		// 书面预警次数
		map.put("process", "02");
		List<Map<String, Object>> list02 = insuredMedicalDetailDao.queryIntegrityIllegalWarn(map);
		Map<String, Object> map02 = list02.size() > 0 ? list02.get(0) : new HashMap<String, Object>();
		map02.put("code", "02");
		map02.put("name", "书面预警");
		list.add(map02);
		// 约谈预警次数interviewWarnNum
		map.put("process", "03");
		List<Map<String, Object>> list03 = insuredMedicalDetailDao.queryIntegrityIllegalWarn(map);
		Map<String, Object> map03 = list03.size() > 0 ? list03.get(0) : new HashMap<String, Object>();
		map03.put("code", "03");
		map03.put("name", "转稽核");
		list.add(map03);
		// 转稽核次数toAuditNum
		map.put("process", "04");
		List<Map<String, Object>> list04 = insuredMedicalDetailDao.queryIntegrityIllegalWarn(map);
		Map<String, Object> map04 = list04.size() > 0 ? list04.get(0) : new HashMap<String, Object>();
		map04.put("code", "04");
		map04.put("name", "约谈");
		list.add(map04);
		// 其它次数otherNum
		map.put("process", "09");
		List<Map<String, Object>> list09 = insuredMedicalDetailDao.queryIntegrityIllegalWarn(map);
		Map<String, Object> map09 = list09.size() > 0 ? list09.get(0) : new HashMap<String, Object>();
		map09.put("code", "09");
		map09.put("name", "其它");
		list.add(map09);
		warnData.put("list", list);
		// 预警
		resultMap.put("warnData", warnData);
		// 稽核
		List<Map<String, Object>> auditList = insuredMedicalDetailDao.queryIntegrityIllegalAudit(map);
		resultMap.put("auditData", auditList.size() > 0 ? auditList.get(0) : new HashMap<String, Object>());
		//
		Map<String, Object> illegalWorkers = new HashMap<String, Object>();
		resultMap.put("illegalWorkers", illegalWorkers);
		return resultMap;
	}

}
